package com.block.sms.service.send;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.service.LogFactory;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsTemplate;
import com.block.sms.dto.SmsBalanceDTO;
import com.block.sms.dto.SmsResultDTO;
import com.block.sms.service.ISmsSendService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class DaHanSmsSendServiceImpl  implements ISmsSendService {

    private static final Logger log = LogFactory.getCommLog();

    @Override
    public SmsResultDTO sendSms(String mobile, String outId, SmsTemplate smsTemplate, SmsConfigInfo smsConfigInfo, JSONObject paramObject) {

        SmsResultDTO  resultDTO = new SmsResultDTO();
        try {
            JSONArray paramArr = paramObject.getJSONArray("paramArr");

            HttpRequest httpRequest = HttpUtil.createPost(smsConfigInfo.getUrl());

            String username = smsConfigInfo.getAccount();
            //格式话短信内容
            String content = StrUtil.format(smsTemplate.getTemplateContext(), paramArr.stream().toArray());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("account", username);
            paramMap.put("password", smsConfigInfo.getSecret());
            paramMap.put("phones", mobile);
            paramMap.put("content", content);
            paramMap.put("sign", smsTemplate.getSmsSign());

            httpRequest.body(JSON.toJSONString(paramMap));

            String bodyResult = httpRequest.execute().body();
            log.info("【大汉三通短信服务】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getUrl(), JSON.toJSONString(paramMap), bodyResult);

            JSONObject resultJson = JSON.parseObject(bodyResult);
            String result = resultJson.getString("result");// 【任信花】尊敬的用户，您的验证码214350如非本人操作，请忽略此短信。

            resultDTO.setData(bodyResult);
            if (StrUtil.equals("0", result)){
                resultDTO.setCode(AppRspCodeConstant.SUCCESS);
                resultDTO.setHttpStatus(result);
                resultDTO.setRequestId(outId);
                resultDTO.setMessage(bodyResult);
                return resultDTO;
            }
            resultDTO.setMessage(bodyResult);
        } catch (Exception exception) {
            log.error(String.format("【大汉三通短信服务】发送发生异常【mobile】%s【code】%s", mobile, paramObject.toJSONString()), exception);
        }
        resultDTO.setCode(AppRspCodeConstant.OPERATION_FAILURE);
        return resultDTO;
    }

    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

}
